package DBLayer;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import ModelLayer.Employee;

public class DBEmployee implements IFDBEmployee{
	

    private  Connection con;
    /** Creates a new instance of DBEmployee */
    public DBEmployee() {
      con = DbConnection1.getInstance().getDBcon();
    }

	public ArrayList<Employee> getAllEmployees(boolean retriveAssociation) {
		//Auto-generated method stub
		 return miscWhere("", retriveAssociation);
	}

	public Employee findEmployee(int empId) {
		//Auto-generated method stub
		 String wClause = "  empID = '" + empId + "'";
	        return singleWhere(wClause);
	}

	public Employee searchEmployeeName(String name) {
		//Auto-generated method stub
        String wClause = "empname like '%" + name + "%'";
        System.out.println("SearchEmployee " + wClause);
        return singleWhere(wClause);
	}
	
	public Employee searchEmployeeLoginName(String loginname) {
		// Auto-generated method stub
        String wClause = "emplogin like '%" + loginname + "%'";
        System.out.println("SearchEmployee " + wClause);
        return singleWhere(wClause);
	}

	public Employee searchEmpId(int empId) {
		//Auto-generated method stub
		String wClause = "empID = '" + empId + "'";
        System.out.println("Search Employee: " + wClause);
        return singleWhere(wClause);
	}

	public int insertEmployee(Employee emp) throws Exception {
		//Auto-generated method stub
		//call to get the next ID number
        int nextID = GetMax.getMaxId("Select max(empID) from employee");
        nextID = nextID + 1;
        System.out.println("next empID = " +  nextID);
  
       int rc = -1;
	   String query="INSERT INTO employee(empID, empname, empaddress, empzip, empsalary, emplogin, emppassword)  VALUES('"+
	  		nextID + "','" +
			emp.getName()  + "','"  +
		    emp.getAddress()  + "','"  +
		    emp.getZipCode()  + "','"  +
		    emp.getSalary()  + "','"  +
		    emp.getLogin()  + "','"  +
            emp.getPassword() + "')";
                     

       System.out.println("insert : " + query);
      try{ // insert new employee +  dependent
          Statement stmt = con.createStatement();
          stmt.setQueryTimeout(5);
     	  rc = stmt.executeUpdate(query);
          stmt.close();
      }//end try
       catch(SQLException ex){
          System.out.println("Employee ikke oprettet");
          throw new Exception ("Employee is not inserted correct");
       }
       return(rc);
	}

	public int updateEmployee(Employee emp) {
		//Auto-generated method stub
		Employee empObj  = emp;
		int rc=-1;

		String query="UPDATE employee SET "+
		 	  "empName ='"+ empObj.getName()+"', "+
		 	  "empAddress ='"+ empObj.getAddress() + "', " +
                          "empZip ='"+ empObj.getZipCode() + "', " +
                          "empSalary ='"+ empObj.getSalary() + "', " +
                          "empLogin ='"+ empObj.getLogin() + "', " +
                          "empPassword ='"+ empObj.getPassword() + "' " +
		          " WHERE empID = '"+ empObj.getEmpId() + "'";
                System.out.println("Update query:" + query);
  		try{ // update Employee
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 	 	rc = stmt.executeUpdate(query);

	 	 	stmt.close();
		}//slut try
	 	catch(Exception ex){
	 	 	System.out.println("Update exception in Employee db: "+ex);
	  	}
		return(rc);
	}

	public int deleteEmployee(int empID) {
		//Auto-generated method stub
		int rc=-1;
		  
	  	String query="DELETE FROM employee WHERE empID = '" +
				empID + "'";
                System.out.println(query);
	  	try{ // delete from employee
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 	  	rc = stmt.executeUpdate(query);
	 	  	stmt.close();
  		}//slut try	
   	        catch(Exception ex){
	 	  	System.out.println("Delete exception in employee db: "+ex);
   	        }
		return(rc);
	}
	
	private Employee singleWhere(String wClause)
    {	
        ResultSet results;
        Employee empObj = new Employee();
        String query =  buildQuery(wClause);
        System.out.println("DbEmployee -singleWhere " + query); 
        try{ // read from project
        	Statement stmt = con.createStatement();
        	stmt.setQueryTimeout(5);
        	results = stmt.executeQuery(query);

	   if( results.next() ){
	       empObj = buildEmployee(results);
               //missing the test on retriveassociation
               
           }//end if
	   stmt.close();
	}//slut try	
	catch(Exception e){
	   System.out.println("Query exception - select employee : "+e);
	   e.printStackTrace();
        }
	return empObj;

    
    }
	
	 //miscWhere is used when more than one laaner is selected and build
    private ArrayList<Employee> miscWhere(String wClause, boolean retrieveAssociation)
	{
		ResultSet results;
		ArrayList<Employee> list = new ArrayList<Employee>();
		
		String query =  buildQuery(wClause);
                System.out.println("DbEmployee " + query); 
  		try{ // read from project
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 		results = stmt.executeQuery(query);
	 	
			while( results.next() ){
		     	 Employee empObj = new Employee();
			 empObj = buildEmployee(results);	
                         list.add(empObj);
                         //missing tes on retriveAssociation
			}//end while
			stmt.close();
			
		}//slut try	
	 	catch(Exception e){
	 		System.out.println("Query exception - select employee : "+e);
			e.printStackTrace();
	 	}
		return list;
	}
    
    private Employee buildEmployee(ResultSet results)
    {
       Employee empObj = new Employee();
       
         try{
               empObj.setEmpId(results.getInt("empID"));
               empObj.setName(results.getString("empname"));
               empObj.setAddress(results.getString("empAddress"));
               empObj.setZipCode(results.getString("empZip"));
               empObj.setCity(results.getString("city"));
               empObj.setSalary(results.getDouble("empSalary"));
               empObj.setLogin(results.getString("empLogin"));
               empObj.setPassword(results.getString("empPassword"));
               
          }
         catch(Exception e)
         {
             System.out.println("building employee object");
         }
        
        return empObj;
        
    }
    
    private String buildQuery(String wClause)
	{
            String query="SELECT empID, empName, empAddress, empZip, city, empSalary, empLogin, empPassword FROM employee,zipcode where empZip=ZipCode"; 
            
           

		if (wClause.length()>0)
			query = query + "  and " + wClause;
			
		return query;
	}
	

	

}
